FILE(GLOB MNN_Metal_SRC ${CMAKE_CURRENT_LIST_DIR}/*.mm ${CMAKE_CURRENT_LIST_DIR}/*.hpp ${CMAKE_CURRENT_LIST_DIR}/*.h ${CMAKE_CURRENT_LIST_DIR}/*.cpp)
FILE(GLOB MNN_Metal_KERNELS_SRC ${CMAKE_CURRENT_LIST_DIR}/*.metal)
option(MNN_METALLIB_SOURCE "Use Metal Source Directly" ON)
add_library(MNNMetal OBJECT ${MNN_Metal_SRC} "${CMAKE_CURRENT_LIST_DIR}/MetalOPRegister.mm")
target_compile_options(MNNMetal PRIVATE -DMNN_METAL_ENABLED=1)
if (MNN_METALLIB_SOURCE)
    target_compile_options(MNNMetal PRIVATE -DMNN_METALLIB_SOURCE)
else()
    message(STATUS "Generating mnn.metallib at ${CMAKE_CURRENT_BINARY_DIR}/mnn.metallib")
    IF(DEFINED SDK_VERSION)
        #Defined by iOS toolchain
        SET(METAL_SDK_PLAT "iphoneos")
    ELSE()
        SET(METAL_SDK_PLAT "macosx")
    ENDIF()
    message(STATUS "Compiling Metal Kernels with ${METAL_SDK_PLAT} SDK")
    add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/mnn.metallib COMMAND xcrun -sdk ${METAL_SDK_PLAT} metal "${MNN_Metal_KERNELS_SRC}" -o ${CMAKE_CURRENT_BINARY_DIR}/mnn.metallib COMMAND_EXPAND_LISTS)
    add_custom_target(MNNMetalLib DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/mnn.metallib COMMENT "Generating mnn.metallib")
    add_dependencies(MNNMetal MNNMetalLib)
    # Adding mnn.metallib into MNN.framework/Resources need provide it as add_library's argument
    list(APPEND MNN_OBJECTS_TO_LINK ${CMAKE_CURRENT_BINARY_DIR}/mnn.metallib)
endif()
set_property(TARGET MNNMetal APPEND_STRING PROPERTY COMPILE_FLAGS "-fobjc-arc")

list(APPEND MNN_OBJECTS_TO_LINK $<TARGET_OBJECTS:MNNMetal>)
